package com.app.couponsharelife.ui.main.sort

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DefaultItemAnimator
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.PrimarySortBean
import com.app.couponsharelife.data.bean.SecondarySortBean
import com.app.couponsharelife.databinding.FragmentSortBinding
import com.app.couponsharelife.ui.adapter.SortDetailAdapter
import com.app.couponsharelife.ui.adapter.SortTypeAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.search.SearchActivity
import com.app.couponsharelife.ui.viewmodel.SortViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.fragment_sort.*
import java.util.*

/**
 * Created by guluwa on 2018/11/21.
 */
class SortFragment : LazyFragment() {

    override val viewLayoutId: Int get() = R.layout.fragment_sort

    private var mViewModel: SortViewModel? = null

    private var selectPosition = 0

    companion object {
        fun newInstance(): SortFragment {
            val fragment = SortFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }

    override fun initViews() {
        (mViewDataBinding as FragmentSortBinding).pageTipBean = PageTipBean("", 0, 0)
        clSerachBar.setOnClickListener {
            val intent=Intent(activity,SearchActivity::class.java)
            intent.putExtra("SearchContent","")
            startActivity(intent)
        }
        initRecyclerView()
    }

    private fun initRecyclerView() {
        mRecyclerViewSort.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
        mRecyclerViewSort.adapter = SortTypeAdapter(arrayListOf(), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                selectPosition = arg1
                getSecondarySorts((arg2 as PrimarySortBean.ListBean).id)
//                mRecyclerViewDetail.scrollToPosition(arg1)
//                val mLayoutManager = mRecyclerViewDetail.layoutManager as androidx.recyclerview.widget.LinearLayoutManager
//                mLayoutManager.scrollToPositionWithOffset(arg1, 0)
            }
        })
        (mRecyclerViewSort.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false

        mRecyclerViewDetail.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
        mRecyclerViewDetail.adapter = SortDetailAdapter(arrayListOf(PageTipBean("", 0, 0)), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                /*val listBean = arg2 as SecondarySortBean.ListBean
                val intent = Intent(context, HomeTypeActivity::class.java)
                intent.putExtra("name", listBean.name)
                intent.putExtra("type", listBean.name)
                intent.putExtra("isCharge", false)
                startActivity(intent)*/
            }
        })
    }

    override fun lazyLoad() {
        val map = HashMap<String, String>()
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel!!.refreshGetPrimarySorts(map, true)
    }

    private fun getSecondarySorts(id: String) {
        val map = HashMap<String, String>()
        map["id"] = id
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel!!.refreshGetSecondarySorts(map, true)
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(SortViewModel::class.java)
        if (!mViewModel!!.getPrimarySorts()!!.hasObservers()) {
            mViewModel!!.getPrimarySorts()!!.observe(this, Observer {
                if (it == null) {
                    (mViewDataBinding as FragmentSortBinding).pageTipBean = parseErrorDate("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {

                    }
                    PageStatus.Error -> {
                        mViewModel!!.refreshGetPrimarySorts(hashMapOf(), false)
                        (mViewDataBinding as FragmentSortBinding).pageTipBean = parseErrorDate(it.error!!.message)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.refreshGetPrimarySorts(hashMapOf(), false)
                        (mViewDataBinding as FragmentSortBinding).pageTipBean = parseErrorDate("暂无数据")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.refreshGetPrimarySorts(hashMapOf(), false)
                        if (it.data!!.code == 1 && it.data.data != null) {
                            handlePrimarySort(it.data.data!!)
                        } else {
                            (mViewDataBinding as FragmentSortBinding).pageTipBean = parseErrorDate("请求失败")
                        }
                    }
                }
            })
            mViewModel!!.getSecondarySorts()!!.observe(this, Observer {
                if (it == null) {
                    (mRecyclerViewDetail.adapter as SortDetailAdapter).setData(parseErrorDate("数据出错啦"))
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        (mRecyclerViewDetail.adapter as SortDetailAdapter).setData(PageTipBean("", 0, 0))
                    }
                    PageStatus.Error -> {
                        mViewModel!!.refreshGetSecondarySorts(hashMapOf(), false)
                        (mRecyclerViewDetail.adapter as SortDetailAdapter).setData(parseErrorDate(it.error!!.message))
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.refreshGetSecondarySorts(hashMapOf(), false)
                        (mRecyclerViewDetail.adapter as SortDetailAdapter).setData(parseErrorDate("暂无数据"))
                    }
                    PageStatus.Content -> {
                        mViewModel!!.refreshGetSecondarySorts(hashMapOf(), false)
                        if (it.data!!.code == 1 && it.data.data != null) {
                            handleSecondarySort(it.data.data!!)
                        } else {
                            (mRecyclerViewDetail.adapter as SortDetailAdapter).setData(parseErrorDate("请求失败"))
                        }
                    }
                }
            })
        }
    }

    private fun handleSecondarySort(data: SecondarySortBean) {
        if (data.list.isNotEmpty() && selectPosition < (mRecyclerViewSort.adapter as SortTypeAdapter).list.size) {
            data.name = (mRecyclerViewSort.adapter as SortTypeAdapter).list[selectPosition].name
            (mRecyclerViewDetail.adapter as SortDetailAdapter).setData(data)
        } else {
            (mRecyclerViewDetail.adapter as SortDetailAdapter).setData(parseErrorDate("暂无二级分类"))
        }
    }

    private fun handlePrimarySort(data: PrimarySortBean) {
        if (data.list.isNotEmpty()) {
            (mViewDataBinding as FragmentSortBinding).pageTipBean = PageTipBean("", 0, 2)
            (mRecyclerViewSort.adapter as SortTypeAdapter).setData(data.list, selectPosition)
            getSecondarySorts(data.list[selectPosition].id)
        } else {
            (mViewDataBinding as FragmentSortBinding).pageTipBean = PageTipBean("暂无数据", R.drawable.ic_data_empty, 1)
        }
    }

    override fun onSaveState(outState: Bundle) {
        super.onSaveState(outState)
        outState.putInt("selectPosition", selectPosition)
    }

    override fun onRestoreState(savedInstanceState: Bundle) {
        super.onRestoreState(savedInstanceState)
        selectPosition = savedInstanceState.getInt("selectPosition")
        lazyLoad()
    }
}